<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Running long JavaScript processes in a web browser (optimized version)</title>

  
    
    <style>

body {
  padding:0;
  margin:1em;
}

#progressbar {
  position:relative;
  width:300px; height:20px;
  border:1px solid black;
  overflow:hidden;
}

#progressbar div {
  background:#316AC5;
  width:0; height:100%;
}
    </style></head><body>
    <p>Sorting, please wait...</p>
    <div id="progressbar"><div style="width: 100%;"></div></div>

    <script>

(function () {

    var i, length, data, el, start;

    // Initialize a few things...
    length = 2500;
    data = [];
    el = document.getElementById("progressbar").firstChild;

    // Setup an array of random integers...
    for (i = 0; i < length; i++) {
        //data[i] = Math.floor(Math.random() * length);
        data[i] = length-i;
    }

    function sort (progressFn) {
        i = 0;

        (function () {
            var j, value, start;

            start = new Date().getTime()
            for (; i < length; i++) {

                for (j = length; j > i; j--) {
                    if (data[j] < data[j - 1]) {
                        value = data[j];
                        data[j] = data[j - 1];
                        data[j - 1] = value;
                    }
                }

                if (new Date().getTime() - start > 40) {
		    i++;
                    setTimeout(arguments.callee, 0);
                    break;
                }
            }

            progressFn(i, length);

        })();
    }

    start = new Date().getTime();
    sort(function (value, total) {
        el.style.width = (100 * value / total) + "%";
        if (value >= total) {
            alert("Total duration: " + ((new Date().getTime() - start) / 1000) + " seconds");
        }
    });

})();

    </script>
  
</body></html>